package io.dy.listerner;

import io.dy.model.WatchThreadPoolRunData;
import org.springframework.context.ApplicationContext;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.context.event.EventListener;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * @author dmj
 * @date 2024年04月18日 下午2:16
 */
public class ContextRefreshedEventListener{

    @EventListener
    public void onApplicationEvent(ContextRefreshedEvent event) {
        System.out.println("事件监听。。。。。。。");
        ApplicationContext context = event.getApplicationContext();
        ScheduledThreadPoolExecutor executor = new ScheduledThreadPoolExecutor(1);
        //获取所有线程池
        Map<String, ThreadPoolExecutor> executors = context.getBeansOfType(ThreadPoolExecutor.class);

        executor.scheduleAtFixedRate(()->{
            List<WatchThreadPoolRunData> watchList = new ArrayList<>();
            executors.forEach((key,value)->{
                watchList.add(
                        WatchThreadPoolRunData.builder()
                                .threadPoolName(key)
                                .watchTime(LocalDateTime.now())
                                .corePoolSize(value.getCorePoolSize())
                                .maximumPoolSize(value.getMaximumPoolSize())
                                .currentPoolSize(value.getPoolSize())
                                .activeCount(value.getActiveCount())
                                .largestPoolSize(value.getLargestPoolSize())
                                .completedTaskCount(value.getCompletedTaskCount())
                                .queueSize(value.getQueue().size()).build()
                );
            });
            System.out.println(watchList);
        },5, 5, TimeUnit.SECONDS);
    }
}
